package P048_EqualsAndHashCode;

import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * equals 覆写hashCode
 *
 * @author xufy1
 */
public class EqualsAndHashCode {


    @Test
    public void test1() {
        Map<Person, Object> map = new HashMap<Person,Object>(){
            {
                put(new Person("张三"), new Object());
                put(new Person("张三"), new Object());
            }
        };
        List<Person> list= new ArrayList<Person>(){
            {
                add(new Person("张三"));
            }
        } ;
        //(o==null ? e==null : o.equals(e)
        boolean b1 = list.contains(new Person("张三"));
        System.out.println(b1);

        /**
         * map 是以数组 保存数据， 数组的下标是 传入元素的hashCode方法返回值
         * 哈希算法的基本要求： 输入任意k, 通过一定算法f(k) ,非可逆输出： k1=k2, f(k1)=f(k2),允许k1 !=k2 ,f(k1)=f(k2)存在
         */
        boolean b2 = map.containsKey(new Person("张三"));
        System.out.println(b2);

    }

}

class Person {

    private String name;

    public Person(String _name) {
        name = _name;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //满足传递性原则
    @Override
    public boolean equals(Object obj) {

        if (obj !=null && obj.getClass()==this.getClass()) {
            Person p = (Person) obj;
            if (p.getName() == null || name == null) {
                return false;
            } else {
//                return name.equalsIgnoreCase(p.getName()+"1");
                return name.equalsIgnoreCase(p.getName());
            }
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
/*
    @Override
    public int hashCode(){
        return new HashCodeBuilder().append(name).toHashCode();
    }*/
}

